﻿using System;
using System.Configuration;
using System.Threading;
using System.Windows;
using NLog;
using MessageBox = Xceed.Wpf.Toolkit.MessageBox;

namespace GemGui
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static readonly Logger s_logger = LogManager.GetCurrentClassLogger();

        // Taken from http://stackoverflow.com/questions/21789899/how-to-create-single-instance-wpf-application-that-restores-the-open-window-when
        // in order to make a singleton WPF application:
        private static readonly Mutex s_mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
        private static MainWindow s_mainWindow = null;

        App()
        {
            InitializeComponent();
        }

        [STAThread]
        static void Main()
        {
            try
            {
                if (s_mutex.WaitOne(TimeSpan.Zero, true))
                {
                    s_logger.Info("----- Starting GemGui -----");

                    var app = new App();
                    s_mainWindow = new MainWindow();
                    app.Run(s_mainWindow);
                    s_mutex.ReleaseMutex();
                }
                else
                {
                    MessageBox.Show("GEM Application is already open.", "GEM", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                }
            }
            catch (ConfigurationErrorsException ex)
            {
                throw; // Cannot recover
            }
            catch (Exception ex)
            {
                if (ex is TypeInitializationException && ex.InnerException is ConfigurationErrorsException)
                {
                    MessageBox.Show(ex.InnerException.Message, "GEM", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                }
                else
                {
                    s_logger.Error(ex, "*** GemGui Unhandled exception caught.");
                }

                throw;
            }
        }
    }
}
